package com.uzai.console.service.ks.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doudian.open.core.AccessToken;
import com.doudian.open.core.AccessTokenBuilder;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.ks.kstoken.KsTokenIdDto;
import com.uzai.console.dto.ks.kstoken.KsTokenInfoDto;
import com.uzai.console.dto.ks.kstoken.KsTokenQuery;
import com.uzai.console.entity.KsToken;
import com.uzai.console.mapper.KsTokenMapper;
import com.uzai.console.service.ks.KsTokenService;
import com.uzai.console.vo.ks.kstoken.KsTokenAuthUrlVo;
import com.uzai.console.vo.ks.kstoken.KsTokenInfoVo;
import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/***
 * 快手联盟
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class KsTokenServiceImpl implements KsTokenService {

    Logger logger = LoggerFactory.getLogger(KsTokenServiceImpl.class);

    @Autowired
    private KsTokenMapper ksTokenMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;

    /**
     * 查询快手联盟列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param ksTokenQuery
     * @return null
     */
    public Page<KsTokenInfoVo> findKsTokenList(KsTokenQuery ksTokenQuery){
        //新建返回到页面的LIST对象
        List<KsTokenInfoVo> ksTokenInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<KsToken> page = new Page<>();
        ksTokenQuery.convert(page);
        ArrayList<KsToken> ksOrderList =  ksTokenMapper.findByList(page, ksTokenQuery);
        if(ksOrderList != null && ksOrderList.size() > 0){
            for (KsToken ksToken : ksOrderList){
                KsTokenInfoVo ksTokenInfoVo = new KsTokenInfoVo();
                BeanUtils.copyProperties(ksToken, ksTokenInfoVo);
                ksTokenInfoVoList.add(ksTokenInfoVo);
            }
        }

        //返回到页面分页对象
        Page<KsTokenInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(ksTokenInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询快手联盟详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param ksTokenIdDto
     * @return null
     */
    public KsTokenInfoVo findKsTokenInfo(KsTokenIdDto ksTokenIdDto){

        if(ksTokenIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        KsToken ksToken = ksTokenMapper.selectById(ksTokenIdDto.getId(), ksTokenIdDto.getMerId());
        if(ksToken == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该快手联盟账号不存在");
        }

        //返回页面对象
        KsTokenInfoVo ksTokenInfoVo = new KsTokenInfoVo();
        //将查询到的对象复制给返回页面对象
        BeanUtils.copyProperties(ksToken, ksTokenInfoVo);

        return ksTokenInfoVo;
    }


    /***
     * 添加快手账号授权
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public KsTokenAuthUrlVo addKsToken(Long merId){
        //快手联盟
        String ksTokenAuthorize =  uzaiConsoleSysConfig.getKsTokenAuthorize();
        String ksTokenAppkey = uzaiConsoleSysConfig.getKsTokenAppkey();
        ksTokenAuthorize = String.format(ksTokenAuthorize, ksTokenAppkey, merId);
        KsTokenAuthUrlVo ksTokenAuthUrlVo = new  KsTokenAuthUrlVo();
        ksTokenAuthUrlVo.setUrl(ksTokenAuthorize);
        return ksTokenAuthUrlVo;
    }

    /**
     * 修改快手账号授权
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param ksTokenInfoDto
     * @return null
     */
    public void updateKsToken(KsTokenInfoDto ksTokenInfoDto){

        if(ksTokenInfoDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主键ID不能为空");
        }

        if(StringUtils.isBlank(ksTokenInfoDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入快手账号名称");
        }

        KsToken ksToken = ksTokenMapper.selectById(ksTokenInfoDto.getId(), ksTokenInfoDto.getMerId());

        if(ksToken == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "联盟不存在");
        }

        Integer now = DateUtil.getNowTime();
        ksToken.setName(ksTokenInfoDto.getName());
        ksToken.setRemark(ksTokenInfoDto.getRemark());
        ksToken.setUpdateTime(now);
        ksTokenMapper.updateById(ksToken);
    }

    /**
     * 删除快手账号
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param ksTokenIdDto
     * @return null
     */
    public void deleteKsToken(KsTokenIdDto ksTokenIdDto){
        if(ksTokenIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主键ID不能为空");
        }
        ksTokenMapper.deleteById(ksTokenIdDto.getId(), ksTokenIdDto.getMerId());
    }

    /**
     * 刷新快手账号授权
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param ksToken
     * @return null
     */
    public void refreshKsToken(KsToken ksToken){
        if(ksToken == null || StringUtils.isBlank(ksToken.getRefreshToken())){
            return;
        }
        int now = DateUtil.getNowTime();
        AccessToken dkAccessToken = AccessTokenBuilder.refresh(ksToken.getRefreshToken());
        if(dkAccessToken != null){
            String accessToken = dkAccessToken.getAccessToken();
            String refreshToken = dkAccessToken.getRefreshToken();
            Long expireIn = Tools.getLong(dkAccessToken.getExpireIn());
            //刷新授权
            ksToken.setAccessToken(accessToken);
            ksToken.setRefreshToken(refreshToken);
            ksToken.setExptime(now + expireIn.intValue());
            ksToken.setUpdateTime(now);
            ksTokenMapper.updateByIdSelective(ksToken);

            logger.info("-刷新快手联盟授权时间-id={}, accessToken={}, refreshToken={}, exptime={}", ksToken.getId(), accessToken, refreshToken, ksToken.getExptime());

        }
    }

    /**
     * 查询所有快手联盟列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param ksTokenQuery
     * @return null
     */
    public List<KsTokenInfoVo> findKsTokenListSelect(KsTokenQuery ksTokenQuery){
        //新建返回到页面的LIST对象
        List<KsTokenInfoVo> ksTokenInfoVoList = new ArrayList<>();
        ArrayList<KsToken> ksOrderList =  ksTokenMapper.findByList(ksTokenQuery);
        if(ksOrderList != null && ksOrderList.size() > 0){
            for (KsToken ksToken : ksOrderList){
                KsTokenInfoVo ksTokenInfoVo = new KsTokenInfoVo();
                BeanUtils.copyProperties(ksToken, ksTokenInfoVo);
                ksTokenInfoVoList.add(ksTokenInfoVo);
            }
        }
        return ksTokenInfoVoList;
    }

    @Override
    public List<KsToken> listKsToken(Long merId, List<Long> ksAccountIds) {
        if (Objects.isNull(merId) || CollectionUtil.isEmpty(ksAccountIds)) {
            return Lists.newArrayList();
        }
        return ksTokenMapper.selectByIds(merId, ksAccountIds);
    }
}
